<?php
if (!isset($_POST['name'])
    || !isset($_POST['description'])
    || !isset($_POST['companyId'])
    || !isset($_POST['latitude'])
    || !isset($_POST['longitude'])
) {
    echo("Missing parameters from add");
    exit();
}
$name = $_POST['name'];
$description = $_POST['description'];
$companyId = $_POST['companyId'];
$latitude = $_POST['latitude'];
$longitude = $_POST['longitude'];

$salary = null;
if (isset($_POST['salary'])) {
    $salary = $_POST['salary'];
}
$jobUrl = null;
if (isset($_POST['jobUrl'])) {
    $jobUrl = $_POST['jobUrl'];
}
$postedDate = null;
if (isset($_POST['postedDate'])) {
    $postedDate = $_POST['postedDate'];
}
$active = null;
if (isset($_POST['active'])) {
    $active = $_POST['active'];
}

// import database connection variables and connectToMysql method
require_once __DIR__ . '/db_config.php';

$mysqli = connectToMysql();

$query = "INSERT INTO location ( latitude, longitude) VALUES ( '$latitude', '$longitude')";
if ($result = $mysqli->query($query)) {
    /* fetch object array */
    $locationId = $mysqli->insert_id;

    $query = "INSERT INTO Job ( name, description, companyId, location, salary, jobUrl, postedDate, active ) VALUES ("
        . "'$name', '$description', '$companyId', '$locationId', '$salary', '$jobUrl', '$postedDate', '$active')";

    if ($result = $mysqli->query($query)) {
        /* fetch object array */
        echo json_encode($mysqli->insert_id, JSON_NUMERIC_CHECK);
    } else {
        print mysqli_error($mysqli);
    }
} else {
    print mysqli_error($mysqli);
}
/* close connection */
$mysqli->close();
?>